#!/bin/bash

# edit area
JAVA_OPTS="-server -Xms1024m -Xmx1024m -Xmn256M -Xss256k \
-XX:+UseParallelGC -XX:ParallelGCThreads=16 -XX:+UseParallelOldGC \
-XX:MaxDirectMemorySize=1024m"


FILE_PATH="$(dirname $(readlink -f $0))"

if [ ! -d "$FILE_PATH/logs" ]
then
   mkdir "$FILE_PATH/logs"
   chown -R gitv:gitv $FILE_PATH
fi

LOG_PATH="$FILE_PATH/logs/app_log.log"

APP_NAME="op-points-screen-service.jar"
RUN_COMMAND="/opt/soft/java8/bin/java $JAVA_OPTS -jar $FILE_PATH/$APP_NAME"
#end

PID_FILE="$FILE_PATH/logs/server.pid"
pid=''

cd $FILE_PATH
start(){
	if [ -e $PID_FILE ]; then  
	   pid=`cat $PID_FILE`
	   if [ "$pid" != '' ];then
		 kill -9 $pid
		 echo 'KILL PID:[ '$pid '] OK!'
	   fi
	fi
        echo 'current shell dir:'`pwd`
        ID=`id -u -n`
	if [ $ID == gitv ];then
            nohup $RUN_COMMAND >$LOG_PATH 2>&1 & echo $! > $PID_FILE
	else
	    su -c "cd $FILE_PATH; nohup $RUN_COMMAND >$LOG_PATH 2>&1 &"
	    pid=`ps -ef|grep java|grep $FILE_PATH/$APP_NAME|grep -v grep|awk '{print $2}'`
	    echo "$pid" > $PID_FILE
	fi
        echo 'START SERVER OK!'
	    echo 'CURRENT PID IS:['`cat $PID_FILE`']'
}
stop(){
	if [ -e $PID_FILE ]; then  
	   pid=`cat $PID_FILE`
	   if [ "$pid" != '' ];then
		kill -9 $pid
        echo 'KILL PID:[ '$pid '] OK!'
        rm $PID_FILE
		echo "SERVER STOP OK!"
	   fi
	fi
}

case "$1" in 
start) 
start 
;; 
stop) 
stop 
;; 
*) 
printf 'Usage: {start|stop} to start or stop server! \n'
exit 1 
;; 
esac
